package adger.me.yili.utils;

import com.google.gson.Gson;
import com.google.gson.internal.$Gson$Types;
import com.orhanobut.logger.Logger;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by heyue on 16/1/29.
 */
public class XHttp {
    public static<T, ResultType> void post(java.lang.String uri, T sendBean,  final XCallback<ResultType> mCallBack){//Class<T> typeCls
        RequestParams params = new RequestParams(uri);
        params.setAsJsonContent(true);
        params.setBodyContent(new Gson().toJson(sendBean));
        x.http().post(params,new Callback.CommonCallback<String>(){//xutils3 返回网页的结果为String

            @Override
            public void onSuccess(String result) {
//                Logger.d(result);
                mCallBack.onSuccess((ResultType)new Gson().fromJson(result, mCallBack.mType));//自己的mCallBack返回的类型
//                mCallBack.onSuccess((ResultType)new Gson().fromJson(result, OrdersBeanTable.class));//自己的mCallBack返回的类型
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mCallBack.onError(ex,isOnCallback);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    };
    public static abstract class XCallback<ResultType>//Class<T> typeCls
    {
        Type mType;

        public XCallback()
        {
            mType = getSuperclassTypeParameter(getClass());
        }

        static Type getSuperclassTypeParameter(Class<?> subclass)
        {
            Type superclass = subclass.getGenericSuperclass();
            if (superclass instanceof Class)
            {
                throw new RuntimeException("Missing type parameter.");
            }
            ParameterizedType parameterized = (ParameterizedType) superclass;
            return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
        }
        public abstract void onError(Throwable ex, boolean isOnCallback);

        public abstract void onSuccess(ResultType bean);
    }


}
